/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef EL_PROTOCOL_FIRMWARE_UPGRADE_HANDLER_H
#define EL_PROTOCOL_FIRMWARE_UPGRADE_HANDLER_H

#include <string>
#include <unordered_map>
#include <functional>
#include <nlohmann/json.hpp>
#include "command_handler_base.h"  // 添加基类头文件

namespace El {
namespace Protocol {

/**
 * @brief 固件升级处理器
 * 提供固件上传和升级相关功能
 */
class FirmwareUpgradeHandler : public CommandHandlerBase {  // 继承自基类
public:
    FirmwareUpgradeHandler() {
        // 初始化升级状态为空闲
        currentStatus_.status = "idle";
        currentStatus_.progress = 0;
        currentStatus_.message = "系统空闲，未开始升级";
    }

    /**
     * @brief 注册固件升级相关的命令处理函数
     * @param handlers 命令处理函数映射表
     */
    void RegisterMethodHandlers(
        std::unordered_map<std::string, std::function<nlohmann::json(const std::string &, const nlohmann::json &)>>
            &handlers);

private:
    // 固件升级相关处理方法
    nlohmann::json HandleFirmwareUpload(const std::string &id, const nlohmann::json &params);
    nlohmann::json HandleFirmwareUpgrade(const std::string &id, const nlohmann::json &params);
    nlohmann::json HandleGetUpgradeStatus(const std::string &id, const nlohmann::json &params);

    // 文件上传状态跟踪
    struct UploadStatus {
        std::string fileName;
        size_t totalSize;
        int totalChunks;
        std::string version;
    };

    // 升级状态跟踪
    struct UpgradeStatus {
        std::string status;     // idle/downloading/downloaded/upgrading/success/error/rollback
        int progress;           // 0-100
        std::string message;    // 状态描述信息
        std::string error_msg;  // 错误信息（保持向后兼容）
    };

    UploadStatus uploadStatus_;
    UpgradeStatus currentStatus_;
};

} // namespace Protocol
} // namespace El

#endif // EL_PROTOCOL_FIRMWARE_UPGRADE_HANDLER_H